package ua.com.hackaton;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.util.Log;


public class CollectorActivity  extends Activity
{
	 Facebook facebook = new Facebook("244565025554051");

	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);

			facebook.authorize(this, new String[] { "email", "read_mailbox" }, new DialogListener() {
				@Override
				public void onComplete(Bundle values) {
					//get information about the currently logged in user
					loadMessagesInfo();     
				}

				@Override
				public void onFacebookError(FacebookError error) {
				}

				@Override
				public void onError(DialogError e) {
				}

				@Override
				public void onCancel() {
				}
			});
			
			Map<String, Integer> callData = fetchCallData();
			Log.v("", callData.toString());
	    }
	    
		private Map<String, Integer> fetchCallData()
		{
			Map<String, Integer> result = new HashMap<String, Integer>();
			Uri allCalls = Uri.parse("content://call_log/calls");
	        Cursor c = managedQuery(allCalls, null, null, null, null);
	        for(String colName : c.getColumnNames())
	            Log.v("Log", "Column Name: " + colName);

	        if (c.moveToFirst())
	        {
	           do{
	               String name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));
	               if(name != null){
	               onMessageFrom(name, result);}
	                
	           } while (c.moveToNext());
	        }
	        return result;
		}

		protected void loadMessagesInfo()
		{
			Map<String, Integer> nameToNumberOfMessagesMap = null;
			try {
				String personalInfo = facebook.request("me");
				String userName = parseUserName(personalInfo);
				
				String inbox = facebook.request("me/inbox");
				nameToNumberOfMessagesMap = parseInbox(inbox);
				nameToNumberOfMessagesMap.remove(userName);
				// TODO pass this data to the listener
			} catch (MalformedURLException e1) {
				Log.v("exception",e1.getLocalizedMessage());
			} catch (IOException e1) {
				Log.v("exception",e1.getLocalizedMessage());
			}   
		}

		private String parseUserName(String personalInfo)
		{
			int nameIndex = personalInfo.indexOf("\"name\"")+"\"name\"".length()+":\"".length();
			return personalInfo.substring(nameIndex, personalInfo.indexOf("\"", nameIndex));
		}

		private static Map<String, Integer> parseInbox(String inbox)
		{
			Map<String, Integer> result = new HashMap<String, Integer>();
			String currentString = inbox;
			int currentIndex = 0;
			int startIndex = 0;
			int endIndex = 0;
			do
			{
				currentIndex = currentString.indexOf("\"from\"");
				currentString = currentString.substring(currentIndex);
				startIndex = currentString.indexOf("\"name\"")
						+ "\"name\"".length() + ":\"".length();
				endIndex = currentString.indexOf("\"", startIndex);
				String name = currentString.substring(startIndex, endIndex);
				currentString = currentString.substring(endIndex);
				onMessageFrom(name, result);
			} while (currentString.contains("\"from\""));

			return result;
		}

	    private static void onMessageFrom(String name, Map<String, Integer> result)
		{
			Integer numMessages = result.get(name);
			if (numMessages == null)
			{
				numMessages = 0;
			}
			numMessages++;
			result.put(name, numMessages);
		}

		@Override
	    public void onActivityResult(int requestCode, int resultCode, Intent data) {
	        super.onActivityResult(requestCode, resultCode, data);

	        facebook.authorizeCallback(requestCode, resultCode, data);
	    }
}
